<template>
  <div class="search">
    <!-- 搜索栏 -->
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
    />
    <!-- 下拉菜单 -->
    <Dropmenu
      :filterCategory="filterCategory"
      @transfer="changePriceFn"
      @transfer1="changeKindFn"
    ></Dropmenu>
    <!-- 商品组件 -->
    <GoosJList :goodsList="goodsList"></GoosJList>
    <!-- 上一页 -->
    <van-button type="small " size="large" color="#7232dd" @click="ShangYiYe"
      >上一页</van-button
    >
    <!-- 下一页 -->
    <van-button type="small " size="large" color="#7232dd" @click="XiaYiYe"
      >下一页</van-button
    >
  </div>
</template>

<script>
// 引入商品 组件
import GoosJList from "@/components/GoosJList.vue";
// 引入下拉菜单 组件
import Dropmenu from "@/components/Dropmenu.vue";
// 导入商品搜索接口请求
import { searchgoods } from "@/utils/http";
export default {
  name: "Search",
  props: [""],
  data() {
    return {
      keyword: "", //搜索栏信息
      page: 1, //页数
      size: 20, //一页多少数据
      order: "desc", //排列顺序，desc表示价格由高到低，asc表示价格由低到高
      categoryId: 0, //类别id，代表下拉菜单中的全部、居家等选项
      sort: "id", //可以是分类id或价格price
      goodsList: [], //商品数据
      filterCategory: [], //商品分类数据
    };
  },

  components: {
    Dropmenu,
    GoosJList,
  },

  computed: {},

  created() {
    this.grtData();
  },

  mounted() {},

  methods: {
    grtData() {
      let params = {
        keyword: this.keyword,
        page: this.page,
        size: this.size,
        order: this.order,
        categoryId: this.categoryId,
        sort: this.sort,
      };
      searchgoods(params).then((res) => {
        // console.log(res);
        this.goodsList = res.data.data.goodsList;
        this.filterCategory = res.data.data.filterCategory;

        // 将filterCategory 这个数组中的所有name 替换成text, 将id 换成value属性,利用字符串的replace方法
        this.filterCategory = JSON.parse(
          JSON.stringify(this.filterCategory)
            .replace(/name/g, "text")
            .replace(/id/g, "value")
        );
        // console.log(this.filterCategory);
      });
    },

    onSearch(val) {
      //点击搜索触发
      this.grtData();
    },
    onCancel() {
      //点击取消触发  返回上一页
      this.$router.go(-1);
    },
    changePriceFn(m) {
      // 切换价格排序
      console.log(m);
      this.order = m;
      this.sort = "price";
      //修改完成，重新调用
      this.grtData();
    },
    changeKindFn(n) {
      // 切换类别
      this.categoryId = n;
      this.size = "id";
      //修改完成，重新调用
      this.grtData();
    },
    XiaYiYe() {
      // 下一页
      this.page++;
      //修改完成，重新调用
      this.grtData();
    },
    ShangYiYe() {
      // 上一页
      if (this.page > 1) {
        this.page--;
        //修改完成，重新调用
        this.grtData();
      } else {
        this.page = 1;
        //修改完成，重新调用
        this.grtData();
      }
    },
  },
};
</script>
<style lang='less' scoped>
</style>